package org.platform.processor.task.check.impl;

import com.mc.mic.core.tool.helper.SpringContextHelper;
import org.platform.dao.mapper.FdSysconfigMapper;
import org.platform.mo.bussmo.task.CheckItemResult;
import org.platform.processor.task.check.ICheckItem;
import org.platform.tool.util.ComUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该类主要用于判断:解调器锁定是否超过阈值
 * <p>
 * 诊断步骤:
 * 1.读取系统阈值
 * 2.计算每个通道的错误次数
 * 3.输入错误信息
 *
 * @author FengJie
 * @date 2018/6/25
 */
public class DemodulatorLockCheckItemImpl implements ICheckItem {
    /**
     * 通道开始列
     * 开始计算通道的列
     */
    private static final int AISLE_START_COLUMN = 26 - 1;
    /**
     * 每个通道的占用的列数
     * 通道1:从 26-44 共计19列
     * 通道2:从 45-63 共计19列
     * ...
     */
    private static final int AISLE_COLUMN_COUNT = 19;

    /**
     * 载波锁定指示 所在列数
     */
    private static final int ZB_COLUMN = 31 - 1;
    /**
     * 位同步指示 所在列数
     */
    private static final int BIT_SYNC_COLUMN = 32 - 1;
    /**
     * 帧同步指示 所在列数
     */
    private static final int FRAME_SYNC_COLUMN = 33 - 1;
    /**
     * 载波阈值对应的数据表id
     */
    private static final String ZB_VALUE_KEY = "ZBValue";
    /**
     * 位同步阈值对应的数据表 id
     */
    private static final String BIT_SYNC_VALUE_KEY = "bitSyncValue";
    /**
     * 帧同步阈值对应的数据表 id
     */
    private static final String FRAME_SYNC_VALUE_KEY = "frameSyncValue";
    /**
     * 锁定状态
     */
    private static final String UN_LOCKING = "失锁";

    private FdSysconfigMapper sysConfigMapper;

    public DemodulatorLockCheckItemImpl() {
        this.sysConfigMapper = SpringContextHelper.getBean(FdSysconfigMapper.class);
    }

    @Override
    public CheckItemResult getCheckResult(String taskSerialNumber, String jobTaskID, File file) throws IOException {
        CheckItemResult result = new CheckItemResult(true, "正常");

        // (载波/位同步/帧同步)的 阈值/总项数/异常数
        double zbValue = Double.valueOf(sysConfigMapper.selectByPrimaryKey(ZB_VALUE_KEY).getCurrentvalue());
        double bitSyncValue = Double.valueOf(sysConfigMapper.selectByPrimaryKey(BIT_SYNC_VALUE_KEY).getCurrentvalue());
        double frameSyncValue = Double.valueOf(sysConfigMapper.selectByPrimaryKey(FRAME_SYNC_VALUE_KEY).getCurrentvalue());
        double count = 0;

        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        Integer lines = ComUtils.longToInteger(reader.lines().count());
        //记录每个通道的错误次数     key:通道号,v:错误的次数
        Map<Integer, Double> zbErrorCountMap = new HashMap<>(lines);
        Map<Integer, Double> bitSyncErrorCountMap = new HashMap<>(lines);
        Map<Integer, Double> frameSyncErrorCountMap = new HashMap<>(lines);

        //第一行为标题
        reader.readLine();

        String line;
        while ((line = reader.readLine()) != null) {
            ++count;
            String[] split = line.split("\t");
            //i等于当前的通道数   (通道数= (所有列数-公共部分列数)/每个通道的列数 )
            for (int i = 1; i <= (split.length - AISLE_START_COLUMN) / AISLE_COLUMN_COUNT; i++) {

                //计算每个通道 载波/位同步/帧同步 的值:  公共部分列数+ 通道数*(载波/位同步/帧同步第一通道列数-公共部分列数)
                if (split[AISLE_START_COLUMN + i * (ZB_COLUMN - AISLE_START_COLUMN)].equals(UN_LOCKING)) {
                    if (!zbErrorCountMap.containsKey(i)) {
                        zbErrorCountMap.put(i, 0D);
                    }
                    zbErrorCountMap.put(i, zbErrorCountMap.get(i) + 1);
                }
                if (split[AISLE_START_COLUMN + i * (BIT_SYNC_COLUMN - AISLE_START_COLUMN)].equals(UN_LOCKING)) {
                    if (!bitSyncErrorCountMap.containsKey(i)) {
                        bitSyncErrorCountMap.put(i, 0D);
                    }
                    bitSyncErrorCountMap.put(i, bitSyncErrorCountMap.get(i) + 1);
                }
                if (split[AISLE_START_COLUMN + i * (FRAME_SYNC_COLUMN - AISLE_START_COLUMN)].equals(UN_LOCKING)) {
                    if (!frameSyncErrorCountMap.containsKey(i)) {
                        frameSyncErrorCountMap.put(i, 0D);
                    }
                    frameSyncErrorCountMap.put(i, frameSyncErrorCountMap.get(i) + 1);
                }
            }
        }
        reader.close();
        inputStreamReader.close();
        fileInputStream.close();

        List<Integer> zbErrorChannelList = new ArrayList<>();
        List<Integer> bitSyncChannelList = new ArrayList<>();
        List<Integer> frameSyncChannelList = new ArrayList<>();
        //判断是否超过预设的阈值
        final double c = count;
        zbErrorCountMap.forEach((channel, errorCount) -> {
            if (errorCount / c > zbValue) {
                result.setStatus(false);
                zbErrorChannelList.add(channel);
            }
        });
        bitSyncErrorCountMap.forEach((channel, errorCount) -> {
            if (errorCount / c > bitSyncValue) {
                result.setStatus(false);
                bitSyncChannelList.add(channel);
            }
        });
        frameSyncErrorCountMap.forEach((channel, errorCount) -> {
            if (errorCount / c > frameSyncValue) {
                result.setStatus(false);
                frameSyncChannelList.add(channel);
            }
        });

        //输入最后所有通道的异常信息
        StringBuffer b1 = new StringBuffer();
        zbErrorChannelList.forEach(channel -> b1.append(channel).append(","));
        String e1 = b1.toString();
        if (e1.length() > 1) {
            e1 = e1.substring(e1.length() - 1);
            result.setConclusion("通道" + e1 + "解调器载波锁定异常");
        }

        StringBuffer b2 = new StringBuffer();
        bitSyncChannelList.forEach(channel -> b2.append(channel).append(","));
        String e2 = b2.toString();
        if (e2.length() > 1) {
            e2 = e2.substring(e2.length() - 1);
            result.setConclusion(result.getConclusion() + "; 通道" + e2 + "解调器位同步锁定异常");
        }

        StringBuffer b3 = new StringBuffer();
        frameSyncChannelList.forEach(channel -> b3.append(channel).append(","));
        String e3 = b3.toString();
        if (e3.length() > 1) {
            e3 = e3.substring(e3.length() - 1);
            result.setConclusion(result.getConclusion() + "; 通道" + e3 + "解调器帧同步锁定异常");
        }
        return result;
    }
}
